package com.dingwei.superiordiary.mvp.presenter;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.base.MyBaseBean;
import com.dingwei.superiordiary.bean.FailsBean;
import com.dingwei.superiordiary.bean.LookUserCenterBean;
import com.dingwei.superiordiary.custom.myCallback;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.ui.activity.LoginActivity;
import com.dingwei.superiordiary.ui.activity.ReportActivity;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.base.URLS;
import com.lihao.baselibrary.base.basePresenter;
import com.lihao.baselibrary.utils.ScreenUtils;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.xutils.http.RequestParams;
import org.xutils.x;

import static com.scwang.smartrefresh.layout.util.DensityUtil.dp2px;

/**
 * Created by lihao on 2017/9/12.
 */

public class LookUserCenterPresenter extends basePresenter {

    private Contract.LookUserCenterView lookUserCenterView;
    private PopupWindow rightPopupWindow;
    private PopupWindow sharePopupWindow;

    public LookUserCenterPresenter(Contract.LookUserCenterView view) {
        super(view);
        this.lookUserCenterView = view;
    }

    public void getUserCenter(String user_id, int page, final boolean isRefresh, boolean isShowDialog) {

        RequestParams rp = new RequestParams(URLS.HOST + URLS.userCenter1);
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());
        rp.addBodyParameter("userid", user_id);
        rp.addBodyParameter("page",page+"");

        x.http().post(rp, new myCallback(BaseActivity.context, LookUserCenterBean.class, isShowDialog, rp) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                LookUserCenterBean bean = (LookUserCenterBean) baseBean;
                if (isRefresh) {
                    lookUserCenterView.onRefresh(bean);
                } else {
                    lookUserCenterView.onLoadMore(bean);
                }

            }

            @Override
            public void fail(FailsBean baseBean, String result) {
                lookUserCenterView.onFail();
            }
        });

    }

    public void showMinePop(View tvShow, final String id, final int position, final String top) {
        View view = LayoutInflater.from(BaseActivity.context).inflate(R.layout.dialog_mine_user_center, null);
        LinearLayout llbg = (LinearLayout) view.findViewById(R.id.ll_bg);
        ImageView img_ding = (ImageView) view.findViewById(R.id.img_ding);
        ImageView img_delete = (ImageView) view.findViewById(R.id.img_delete);
        if (top.equals("1")){
            img_ding.setImageResource(R.mipmap.ic_cancel_top);
        }else {
            img_ding.setImageResource(R.mipmap.ic_set_top);
        }
        img_ding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rightPopupWindow.dismiss();
                SetActivityTop(id, position,top);
            }
        });
        img_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rightPopupWindow.dismiss();
                ActivityDetele(id, position);
            }
        });
        rightPopupWindow = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        rightPopupWindow.setContentView(view);
        rightPopupWindow.setFocusable(true);
        rightPopupWindow.setTouchable(true);
        rightPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        rightPopupWindow.setOutsideTouchable(true);
        int windowPos[] = calculatePopWindowPos(tvShow, view, llbg);
        rightPopupWindow.showAtLocation(view, Gravity.TOP | Gravity.START, windowPos[0], windowPos[1]);
        backgroundAlpha(0.4f);
        rightPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1);
            }
        });
    }

    public void showOtherPop(View tvShow, final String id, final int position) {
        View view = LayoutInflater.from(BaseActivity.context).inflate(R.layout.dialog_other_user_center, null);
        LinearLayout llbg = (LinearLayout) view.findViewById(R.id.ll_bg);
        ImageView img_jubao = (ImageView) view.findViewById(R.id.img_jubao);
        ImageView imgcollect = (ImageView) view.findViewById(R.id.img_collect);
        img_jubao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rightPopupWindow.dismiss();
                Intent intent = new Intent(BaseActivity.context, ReportActivity.class);
                intent.putExtra("id", id);
                intent.putExtra("tip_type", "tie");
                BaseActivity.context.startActivity(intent);
            }
        });
        imgcollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rightPopupWindow.dismiss();
                activityCollect(id, position);
            }
        });
        rightPopupWindow = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        rightPopupWindow.setContentView(view);
        rightPopupWindow.setFocusable(true);
        rightPopupWindow.setTouchable(true);
        rightPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        rightPopupWindow.setOutsideTouchable(true);
        int windowPos[] = calculatePopWindowPos(tvShow, view, llbg);
        rightPopupWindow.showAtLocation(view, Gravity.TOP | Gravity.START, windowPos[0], windowPos[1]);
        backgroundAlpha(0.4f);
        rightPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1);
            }
        });
    }

    private void backgroundAlpha(float f) {
        WindowManager.LayoutParams lp = BaseActivity.context.getWindow().getAttributes();
        lp.alpha = f;
        BaseActivity.context.getWindow().setAttributes(lp);
    }

    /**
     * 计算出来的位置，y方向就在anchorView的上面和下面对齐显示，x方向就是与屏幕右边对齐显示
     * 如果anchorView的位置有变化，就可以适当自己额外加入偏移来修正
     *
     * @param anchorView  呼出window的view
     * @param contentView window的内容布局
     * @return window显示的左上角的xOff, yOff坐标
     */
    private int[] calculatePopWindowPos(final View anchorView, final View contentView, LinearLayout llBg) {
        final int windowPos[] = new int[2];
        final int anchorLoc[] = new int[2];
        // 获取锚点View在屏幕上的左上角坐标位置
        anchorView.getLocationOnScreen(anchorLoc);
        final int anchorHeight = anchorView.getHeight();
        // 获取屏幕的高宽
        final int screenHeight = ScreenUtils.getScreenHeight(anchorView.getContext());
        final int screenWidth = ScreenUtils.getScreenWidth(anchorView.getContext());
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 计算contentView的高宽
        final int windowHeight = contentView.getMeasuredHeight();
        final int windowWidth = contentView.getMeasuredWidth();
        // 判断需要向上弹出还是向下弹出显示
        final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);
        if (isNeedShowUp) {
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] - windowHeight;
            llBg.setPadding(0, 0, 0, dp2px(10));
            llBg.setBackgroundResource(R.drawable.pic2t);
        } else {
            llBg.setPadding(0, dp2px(10), 0, 0);
            llBg.setBackgroundResource(R.drawable.pic1j);
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] + anchorHeight;
        }
        return windowPos;
    }

    public void activityCollect(String id, final int position) {
        RequestParams rp = new RequestParams(URLS.HOST + URLS.ActivityCollect);
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());
        rp.addBodyParameter("id", id);
        rp.addBodyParameter("action", "1");
        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, rp) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                lookUserCenterView.collectSuccess(position);
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }
    public void SetActivityTop(String id, final int position, final String top) {
        RequestParams rp = new RequestParams(URLS.HOST + URLS.SetActivityTop);
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());
        rp.addBodyParameter("id", id);
        if (top.equals("1")){
            rp.addBodyParameter("top", "0");
        }else {
            rp.addBodyParameter("top", "1");
        }
        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, rp) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                lookUserCenterView.SetActivityTopSuccess(position,top);
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }
    public void ActivityDetele(String id, final int position) {
        RequestParams rp = new RequestParams(URLS.HOST + URLS.DELETE_MY_RELEASE);
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());
        rp.addBodyParameter("id", id);
        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, rp) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                lookUserCenterView.DeleteSuccess(position);
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }


    public void showSharePopupWindow(View tvShow, final LookUserCenterBean.DataBean.ListBean bean, int position, final UMShareListener shareListener) {
        View view = LayoutInflater.from(BaseActivity.context).inflate(R.layout.dialog_index_share, null);
        ImageView imgurl = (ImageView) view.findViewById(R.id.img_url);
        ImageView imgzone = (ImageView) view.findViewById(R.id.img_zone);
        ImageView imgpengyouquan = (ImageView) view.findViewById(R.id.img_pengyouquan);
        ImageView imgqq = (ImageView) view.findViewById(R.id.img_qq);
        ImageView imgwechat = (ImageView) view.findViewById(R.id.img_wechat);
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sharePopupWindow.dismiss();
                UMWeb web;
                web = new UMWeb(bean.share_data.url);
                web.setTitle(bean.share_data.title);
                if (TextUtils.isEmpty(bean.share_data.img)) {
                    web.setThumb(new UMImage(BaseActivity.context, R.drawable.pic45));
                } else {
                    web.setThumb(new UMImage(BaseActivity.context, bean.share_data.img));
                }
                web.setDescription(bean.share_data.desc);
                ShareAction shareAction = new ShareAction(BaseActivity.context);
                shareAction.withMedia(web);
                shareAction.withText("111111");
                shareAction.setCallback(shareListener);
                switch (view.getId()) {
                    case R.id.img_qq:
                        shareAction.setPlatform(SHARE_MEDIA.QQ);
                        shareAction.share();
                        break;
                    case R.id.img_zone:
                        shareAction.setPlatform(SHARE_MEDIA.QZONE);
                        shareAction.share();
                        break;
                    case R.id.img_pengyouquan:
                        shareAction.setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE);
                        shareAction.share();
                        break;
                    case R.id.img_wechat:
                        shareAction.setPlatform(SHARE_MEDIA.WEIXIN);
                        shareAction.share();
                        break;
                }

            }
        };
        imgurl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sharePopupWindow.dismiss();
                ClipboardManager cm = (ClipboardManager) BaseActivity.context.getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(bean.share_data.url);
                Toast.makeText(BaseActivity.context, "复制成功，可以发给朋友们了。", Toast.LENGTH_LONG).show();
            }
        });
        imgzone.setOnClickListener(listener);
        imgpengyouquan.setOnClickListener(listener);
        imgqq.setOnClickListener(listener);
        imgwechat.setOnClickListener(listener);

        sharePopupWindow = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        sharePopupWindow.setContentView(view);
        sharePopupWindow.setFocusable(true);
        sharePopupWindow.setTouchable(true);
        sharePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        sharePopupWindow.setOutsideTouchable(true);


        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int measuredHeight = view.getMeasuredHeight();
        int[] location = new int[2];
        tvShow.getLocationOnScreen(location);
        sharePopupWindow.showAtLocation(tvShow, Gravity.NO_GRAVITY, 0, location[1] - measuredHeight);

    }

    public void shareSuccess(String id) {
        RequestParams rp = new RequestParams(URLS.HOST + URLS.shareSucc);
        rp.addBodyParameter("id", id);
        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, rp) {
            @Override
            public void back(MyBaseBean baseBean, String result) {

            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }

    public void like(String id, final int position) {
        if (!BaseActivity.value.getIsLogin()) {
            Intent intent = new Intent(BaseActivity.context, LoginActivity.class);
            BaseActivity.context.startActivity(intent);
            return;
        }
        RequestParams rp = new RequestParams(URLS.HOST + URLS.LIKES);
        rp.addBodyParameter("id", id);
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());

        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                showToast("点赞成功");
                lookUserCenterView.likeSuccess(position);
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }

    public void attentionAction(String consumer_id, String action) {
        RequestParams rp = new RequestParams(URLS.HOST+URLS.attentionAction);
        rp.addBodyParameter("userid", consumer_id);
        rp.addBodyParameter("action", action);
        rp.addBodyParameter("sessionid",BaseActivity.value.getToken());
        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, rp) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                lookUserCenterView.attentionActionSuccess();
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }

    public void joinBlackList(String consumer_id) {
        RequestParams rp = new RequestParams(URLS.HOST + "user/joinBlackList");
        rp.addBodyParameter("userid", consumer_id);
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());
        x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, rp) {
            @Override
            public void back(MyBaseBean baseBean, String result) {
                showToast("已拉黑");
                lookUserCenterView.joinBlackListSuccess();
            }

            @Override
            public void fail(FailsBean baseBean, String result) {
            }
        });
    }


    private PopupWindow popupWindow;


    public void showMeunPopupWindow(View tvShow, final int is_black) {
        View view = LayoutInflater.from(BaseActivity.context).inflate(R.layout.pop_meun123, null);
        TextView tvlahei = (TextView) view.findViewById(R.id.tv_lahei);
        LinearLayout jubao = (LinearLayout) view.findViewById(R.id.jubao);
        LinearLayout lahei = (LinearLayout) view.findViewById(R.id.lahei);
        ImageView imgcollect = (ImageView) view.findViewById(R.id.img_collect);
        LinearLayout llbg = (LinearLayout) view.findViewById(R.id.ll_bg);


        if (is_black==0){
            tvlahei.setText("拉黑");
        }else {
            tvlahei.setText("已拉黑");
        }

        jubao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                lookUserCenterView.jubao();
            }
        });

        lahei.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                if (is_black==0){
                    lookUserCenterView.lahei();
                }else {
                    showToast("黑名单已添加，请勿重复操作。取消请前往设置-隐私设置-黑名单设置操作。");
                }
            }
        });

        popupWindow = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(view);
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);

        final int windowPos[] = new int[2];
        final int anchorLoc[] = new int[2];
        // 获取锚点View在屏幕上的左上角坐标位置
        tvShow.getLocationOnScreen(anchorLoc);
        final int anchorHeight = tvShow.getHeight();
        // 获取屏幕的高宽
        final int screenHeight = ScreenUtils.getScreenHeight(tvShow.getContext());
        final int screenWidth = ScreenUtils.getScreenWidth(tvShow.getContext());
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 计算contentView的高宽
        final int windowHeight = view.getMeasuredHeight();
        final int windowWidth = view.getMeasuredWidth();
        // 判断需要向上弹出还是向下弹出显示
        final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);
        if (isNeedShowUp) {
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] - windowHeight;
            llbg.setPadding(0, 0, 0, dp2px(10));
            llbg.setBackgroundResource(R.drawable.pic2t);
        } else {
            llbg.setPadding(0, dp2px(10), 0, 0);
            llbg.setBackgroundResource(R.mipmap.ic_duobianxing);
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] + anchorHeight;
        }
        popupWindow.showAtLocation(view, Gravity.TOP | Gravity.START, windowPos[0], windowPos[1]);
        backgroundAlpha(0.4f);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1);
            }
        });
    }


}



